<template>
    <div>
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchFrom" ref="searchFrom" class="demo-form-inline" style="text-align:center">
            <el-form-item label="首字母" prop="firstLetter">
                <el-input v-model="searchFrom.firstLetter" placeholder="首字母"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="searchFrom.name" placeholder="名称"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchBtn()">查询</el-button>
                <el-button type="warning" icon="el-icon-refresh" @click="resetSearchForm()">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="tableData" stripe style="width: 100%">
            <el-table-column prop="id" label="编号"/>
            <el-table-column prop="name" label="品牌名称"/>
            <el-table-column prop="firstLetter" label="首字母"/>
            <el-table-column prop="sort" label="排序等级"/>
            <el-table-column label="品牌制造商">
                <template slot-scope="scope">
                    <span v-if="scope.row.factoryStatus === 1"><el-button size="mini"
                                                                          type="success">是</el-button></span>
                    <span v-if="scope.row.factoryStatus === 0"><el-button size="mini"
                                                                          type="danger">不是</el-button></span>
                </template>
            </el-table-column>
            <el-table-column prop="logo" label="品牌Logo">
                <!--插入图片链接的代码-->
                <template slot-scope="scope">
                    <img  :src="scope.row.logo" alt="" style="width: 100px;height: 100px">
                </template>
            </el-table-column>
            <el-table-column prop="bigPic" label="专区大图">
                <!--插入图片链接的代码-->
                <template slot-scope="scope">
                    <img  :src="scope.row.bigPic" alt="" style="width: 100px;height: 100px">
                </template>
            </el-table-column>
            <el-table-column label="是否显示">
                <template slot-scope="scope">
                    <span v-if="scope.row.showStatus === 0"><el-button size="mini" type="danger">隐藏</el-button></span>
                    <span v-if="scope.row.showStatus === 1"><el-button size="mini" type="success">显示</el-button></span>
                </template>
            </el-table-column>
            <el-table-column prop="addtime" label="创建时间"/>
            <el-table-column
                    label="品牌故事"
                    width="180">
                <template slot-scope="scope">
                    <el-input
                            type="textarea"
                            v-model="scope.row.brandStory"
                            :autosize="{ minRows: 2, maxRows: 4}">
                    </el-input>
                </template>
            </el-table-column>
            <el-table-column align="right">
                <template slot="header">
                    <span style="margin-right:30px">操作</span>
                    <el-button size="mini" type="primary" @click="handleAdd()">添加</el-button>
                </template>
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="block" style="text-align:center">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[1, 2, 5, 10,20]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <!--添加/修改弹出框-->
        <el-dialog title="详细信息" :visible.sync="dialogVisible" width="600px">
            <!--添加表单-->
            <el-form :model="brandForm" :rules="rules" ref="brandForm" class="demo-brandForm">
                <input v-model="brandForm.id" style="display: none"/>
                <el-form-item label="品牌名称" label-width="120px" prop="name" style="width: 500px">
                    <el-input v-model="brandForm.name"/>
                </el-form-item>
                <el-form-item label="首字母" label-width="120px" prop="firstLetter" style="width: 500px">
                    <el-input v-model="brandForm.firstLetter"/>
                </el-form-item>
                <el-form-item label="排序" label-width="120px" prop="sort" style="width: 500px">
                    <el-input-number v-model="brandForm.sort" :min="1"/>
                </el-form-item>
                <el-form-item label-width="120px" label="品牌Logo" prop="logo">
                    <div>
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:12188/ss/user/upload"
                                :show-file-list="false"
                                :headers="headers"
                                :on-success="handleAvatarSuccessByLogo"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="brandForm.logo" :src="brandForm.logo" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label-width="120px" label="专区大图" prop="bigPic">
                    <div>
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:12188/ss/user/upload"
                                :show-file-list="false"
                                :headers="headers"
                                :on-success="handleAvatarSuccessByBigPic"
                                :before-upload="beforeAvatarUpload">
                            <img v-if="brandForm.bigPic" :src="brandForm.bigPic" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="是否是品牌制造商" label-width="125px" prop="factoryStatus">
                    <el-radio-group v-model="brandForm.factoryStatus" style="width: 500px">
                        <el-radio :label="1" border>是</el-radio>
                        <el-radio :label="0" border>否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否隐藏" label-width="120px">
                    <el-radio-group v-model="brandForm.showStatus" style="width: 500px">
                        <el-radio :label="0" border>隐藏</el-radio>
                        <el-radio :label="1" border>不隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="添加时间" label-width="120px" required style="width: 500px">
                    <el-form-item prop="addtime">
                        <el-date-picker type="date" placeholder="选择日期" v-model="brandForm.addtime"/>
                    </el-form-item>
                </el-form-item>
                <el-form-item label="品牌故事" label-width="120px" prop="brandStory" style="width: 500px">
                    <el-input type="textarea" v-model="brandForm.brandStory"></el-input>
                </el-form-item>
            </el-form>
            <!--dialog的底部按钮-->
            <span slot="footer" class="dialog-footer">
                <el-button @click="resetForm()">取 消</el-button>
                <el-button type="primary" @click="submitForm('brandForm')">确 定</el-button>
             </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        data: function () {
            // 自定义验证规则 验证添加和修改时的品牌名字是否可用
            const checkName = (rule, value, callback) => {
                this.$http.get("/cs/brand/checkName?name=" + value + "&id=" + this.brandForm.id)
                    .then((response) => {
                        if (response.data.resultCode === 5008) {
                            callback(new Error('该名称已存在！'));
                        } else {
                            callback();
                        }
                    })
            };
            return {
                tableData: [],
                headers: {
                    myAuthorization: window.localStorage.getItem("token"),
                },
                total: 0, // 总条数
                pageNum: 1, // 当前页数
                pageSize: 5, // 每页显示几条
                searchFrom: {},
                treeData: [],
                dialogVisible: false,
                brandForm: {},
                rules: {
                    name: [
                        {required: true, message: '请输入品牌名称', trigger: 'blur'},
                        {trigger: 'blur', validator: checkName}//自定义验证:调方法
                    ],
                    firstLetter: [
                        {required: true, message: '请输入首字母', trigger: 'blur'},
                        {required: true, pattern: /^[A-Z]?$/, message: '只能是一个大写字母', trigger: 'blur'}
                    ],
                    addtime: [
                        {required: true, message: '请选择日期', trigger: 'change'}
                    ],
                    desc: [
                        {required: true, message: '请填写活动形式', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            // 重置表格
            resetSearchForm() {
                this.searchFrom = {}
                this.getAllBrand();
            },
            // 查询表单提交
            searchBtn() {
                this.searchFrom.firstLetter = this.searchFrom.firstLetter.toUpperCase()
                this.pageNum = 1;
                this.getAllBrand();
            },
            //每页显示几条改变
            handleSizeChange(val) {
                this.pageSize = val;
                this.getAllBrand();
            },
            // 当前是第几页改变
            handleCurrentChange(val) {
                this.pageNum = val;
                this.getAllBrand();
            },
            // 获得表格数据
            getAllBrand() {
                this.$http.post('cs/brand/queryAll?pageSize=' + this.pageSize + '&pageNum=' + this.pageNum, this.searchFrom)
                    .then(res => {
                        this.tableData = res.data.t.list;
                        this.total = res.data.t.total
                    })
            },

            // 添加按钮
            handleAdd() {
                // 设置添加的默认值
                this.brandForm = {showStatus: 1, factoryStatus: 1, sort: 1,bigPic:'',logo:''}
                this.dialogVisible = true;
            },
            // 编辑按钮
            handleEdit(row) {
                this.brandForm = JSON.parse(JSON.stringify(row));
                this.dialogVisible = true;
            },

            // 删除按钮
            handleDelete(row) {
                this.$confirm('此操作将永久删除该品牌, 是否继续?', '提示', {
                    confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', center: true
                }).then(() => {
                    this.$http.delete("cs/brand/delete/" + row.id).then(res => {
                        if (Number(res.data.resultCode) === 2000) {
                            this.$message({type: 'success', message: '删除成功!'});
                            this.getAllBrand();
                        } else {
                            this.$message({type: 'error', message: '系统异常'});
                        }
                    })
                }).catch(() => {
                    this.$message({type: 'info', message: '已取消删除'});
                });
            },


            // 表单提价
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        if (this.brandForm.id === undefined) {
                            // 执行添加操作
                            this.$http.post("cs/brand/insert", this.brandForm).then(res => {
                                if (Number(res.data.resultCode) === 2000) {
                                    this.$message({type: 'success', message: '恭喜你，添加成功'});
                                    this.dialogVisible = false;
                                    this.getAllBrand();
                                } else {
                                    this.$message({type: 'error', message: '系统异常'});
                                }
                            })
                        } else {
                            // 执行修改操作
                            this.$http.put("cs/brand/update", this.brandForm).then(res => {
                                if (Number(res.data.resultCode) === 2000) {
                                    this.$message({type: 'success', message: '恭喜你，修改成功'});
                                    this.dialogVisible = false;
                                    this.getAllBrand();
                                } else {
                                    this.$message({type: 'error', message: '系统异常'});
                                }
                            })
                        }
                    }
                });
            },

            // 重置表单
            resetForm() {
                this.brandForm = {}
                this.dialogVisible = false;
            },
            // 上传图片之前
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isGIF = file.type === 'image/gif';
                const isPNG = file.type === 'image/png';
                const isBMP = file.type === 'image/bmp';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG && !isGIF && !isPNG && !isBMP) {
                    this.common.errorTip('上传图片必须是JPG/GIF/PNG/BMP 格式!');
                }
                if (!isLt2M) {
                    this.common.errorTip('上传图片大小不能超过 2MB!');
                }
                return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
            },
            // 品牌logo上传成功回调
            handleAvatarSuccessByLogo(res, file) {
                this.brandForm.logo = res.t;
                console.log("logo",this.brandForm.logo)
            },
            // 专区大图上传成功回调
            handleAvatarSuccessByBigPic(res, file) {
                this.brandForm.bigPic = res.t;
                console.log("bigPic",this.brandForm.bigPic)
            },


        },
        mounted() {
            this.getAllBrand();
        }
    }
</script>

<style scoped>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>